
package com.kugou.game.sdk.ui.activity;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnModifyPasswordListener;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.Rx;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述:修改用户密码
 * 
 * @author liux
 * @since 2013-12-17 上午09:43:05
 */
public class ModifyPasswordActivity extends BaseCommonTitleFragmentActivity implements
        OnClickListener {
    /**
     * 消息相关常量
     */
    private static final int MSG_MODIFY_PASSWORD = 0;

    private static final int MSG_MODIFY_PASSWORD_SUCCESS = 1;

    private static final int MSG_MODIFY_PASSWORD_FAILE = 2;

    /**
     * 页面控件
     */
    private TextView tvUserName;

    private EditText etOldPassword;

    private EditText etNewPassword;

    private Button btnSubmit;

    private Button btnBackToGame;

    private View layoutMainView;

    private LinearLayout layoutResult;

    private LoadingView loadingView;

    private TextView tvInputErrorTip, tvForgetPassword, tvNewPswTips;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.PORTRAIT) {
            layoutId = Rx.layout.kg_activity_modify_user_password;
        } else {
            layoutId = Rx.layout.kg_activity_modify_user_password_land;
        }
        if (layoutId != 0) {
            setContentView(layoutId);
            // 设置标题
            setCommonTitle(Rx.string.kg_modify_user_password_title);
            // 设置View界面
            initViews();
        } else {
            showToast(Rx.string.kg_layout_not_found);
        }
    }

    /**
     * 初始化界面控件
     */
    private void initViews() {
        tvNewPswTips = (TextView) findViewById(Rx.id.kg_tv_new_password_tips);
        tvInputErrorTip = (TextView) findViewById(Rx.id.kg_tv_modify_password_tips);
        tvInputErrorTip.setVisibility(View.GONE);
        tvForgetPassword = (TextView) findViewById(Rx.id.kg_tv_forget_password);
        tvForgetPassword.setOnClickListener(this);
        layoutMainView = findViewById(Rx.id.kg_layout_modiy_user_password);
        layoutResult = (LinearLayout) findViewById(Rx.id.kg_layout_summit_successed);
        loadingView = (LoadingView) findViewById(Rx.id.kg_loading);
        loadingView.setText("正在操作，请稍候...");
        // 用户名
        tvUserName = (TextView) findViewById(Rx.id.kg_tv_username);
        User userData = UserManager.getInstance().getCurrentUserInternal();
        if (userData != null) {
            tvUserName.setText(userData.getAccountName());
        }
        // 旧密码
        etOldPassword = (EditText) findViewById(Rx.id.kg_et_original_password);
        String oldPsd = getIntent().getStringExtra("password");
        if (!TextUtils.isEmpty(oldPsd)) {
            etOldPassword.setText(oldPsd);
        }
        // etOldPassword.setOnFocusChangeListener(new OnFocusChangeListener() {
        //
        // @Override
        // public void onFocusChange(View v, boolean hasFocus) {
        // String str = etOldPassword.getText().toString();
        // if (!TextUtils.isEmpty(str)) {
        // checkOldPassword();
        // }
        // }
        // });

        // 新密码
        etNewPassword = (EditText) findViewById(Rx.id.kg_et_new_password);
        etNewPassword.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String str = etNewPassword.getText().toString();
                if (!TextUtils.isEmpty(str)) {
                    checkNewPassword();
                }
            }
        });

        // 修改成功后 返回游戏按钮
        btnBackToGame = (Button) findViewById(Rx.id.kg_btn_back_to_the_game);
        btnBackToGame.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
                finish();
            }
        });

        // 提交按钮
        btnSubmit = (Button) findViewById(Rx.id.kg_btn_summit);
        btnSubmit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });

    }

    /**
     * 点击提交按钮
     */
    private void submit() {
        User userData = UserManager.getInstance().getCurrentUserInternal();
        if (userData == null || !userData.isRegistered()) {
            showToast("请先登录");
            return;
        }

        if (checkNewPassword()) {
            hideSoftInput(this);
            showLoadingView();
            sendEmptyBackgroundMessage(MSG_MODIFY_PASSWORD);
        }
    }

    /**
     * 检查新密码输入是否正确
     * 
     * @return
     */
    private boolean checkNewPassword() {
        String text = etNewPassword.getText().toString();
        if (isPasswordCorrect(text)) {
            // hideErrorTips();
            tvNewPswTips.setVisibility(View.GONE);
            return true;
        } else {
            // setAndShowErrorTips("您输入的新密码不正确");
            tvNewPswTips.setVisibility(View.VISIBLE);
            return false;
        }
    }

    /**
     * 检查旧密码输入是否正确
     * 
     * @return
     */
    private boolean checkOldPassword() {
        String text = etOldPassword.getText().toString().trim();
        User user = UserManager.getInstance().getCurrentUserInternal();
        if (user != null) {
            String psd = user.getPassword();
            if (TextUtils.isEmpty(psd) && !TextUtils.isEmpty(text)) {
                return checkOldPwdWhenNoPwd(text);
            }
            if ((TextUtils.isEmpty(psd) && !TextUtils.isEmpty(text)) || text.equals(psd)) {
                hideErrorTips();
                return true;
            } else {
                setAndShowErrorTips("您输入的旧密码不正确");
                return false;
            }
        }
        return true;
    }

    /**
     * 当使用token登陆时，检查方法和使用密码登陆时的检查方法不一样
     * 
     * @param text 旧密码框里的字符
     * @return
     */
    private boolean checkOldPwdWhenNoPwd(String text) {
        if (isPasswordCorrect(text)) {
            hideErrorTips();
            return true;
        } else {
            setAndShowErrorTips("您输入的旧密码不正确");
            return false;
        }
    }

    /**
     * 检查密码格式
     * 
     * @param password
     * @return
     */
    private boolean isPasswordCorrect(String password) {
        if (!TextUtils.isEmpty(password)) {
            Pattern pattern = Pattern.compile("^[0-9a-zA-Z]{6,16}$");
            Matcher matcher = pattern.matcher(password);
            return matcher.find();
        }
        return false;
    }

    /**
     * 弹出错误提示栏
     */
    private void setAndShowErrorTips(String errorMsg) {
        tvInputErrorTip.setVisibility(View.VISIBLE);
        tvInputErrorTip.setText(errorMsg);
    }

    /**
     * 隐藏错误提示栏
     */
    private void hideErrorTips() {
        tvInputErrorTip.setVisibility(View.INVISIBLE);
    }

    /**
     * 正在加载时的页面显示
     */
    private void showLoadingView() {
        layoutMainView.setVisibility(View.GONE);
        layoutResult.setVisibility(View.GONE);
        loadingView.setVisibility(View.VISIBLE);
    }

    /**
     * 正常情况的页面显示
     */
    private void showMainView() {
        layoutMainView.setVisibility(View.VISIBLE);
        layoutResult.setVisibility(View.GONE);
        loadingView.setVisibility(View.GONE);
    }

    /**
     * 修改成功后的页面显示
     */
    private void showResultView() {
        layoutMainView.setVisibility(View.GONE);
        layoutResult.setVisibility(View.VISIBLE);
        loadingView.setVisibility(View.GONE);
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        switch (msg.what) {
            case MSG_MODIFY_PASSWORD:
                // 获取请求相关参数
                String userName = UserManager.getInstance().getCurrentUserInternal()
                        .getAccountName();
                String oldPwd = etOldPassword.getText().toString();
                String newPwd = etNewPassword.getText().toString();
                // 发出修改密码请求
                final Message message = new Message();
                UserManager.getInstance().modifyPassword(userName, oldPwd, newPwd,
                        new OnModifyPasswordListener() {
                            @Override
                            public void onSuccess() {
                                message.what = MSG_MODIFY_PASSWORD_SUCCESS;
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                                message.what = MSG_MODIFY_PASSWORD_FAILE;
                                message.obj = errorMsg;
                            }
                        });
                sendUiMessage(message);
                break;
        }
    };

    @Override
    public void handleUiMessage(Message msg) {
        switch (msg.what) {
            case MSG_MODIFY_PASSWORD_SUCCESS:// 修改密码成功
                // 显示修改成功后的页面
                showResultView();
                // 通知登录页面显示修改后的信息
                Intent intent = new Intent(SDKActions.ACTION_GET_NEW_PASSWORD);
                intent.putExtra(USER_NICKNAME_KEY, tvUserName.getText().toString().trim());
                intent.putExtra(USER_PASSWORD_KEY, etNewPassword.getText().toString().trim());
                sendBroadcast(intent);
                break;
            case MSG_MODIFY_PASSWORD_FAILE:// 修改密码失败
                String errorMsg = (String) msg.obj;
                showMainView();

                if (!TextUtils.isEmpty(errorMsg)) {
                    showToast(errorMsg);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        if (v == tvForgetPassword) {
            getBackPassword();
        }
    }

    /**
     * 跳转到找回密码页面
     */
    private void getBackPassword() {
        hideSoftInput(this);
        Intent intent = new Intent(ModifyPasswordActivity.this, GetBackPasswordActivity.class);
        intent.putExtra(USER_NICKNAME_KEY, tvUserName.getText().toString().trim());
        startActivity(intent);
    }
}
